<template>
  <div class="top">
    <img class="logo" src="@/assets/image/logo.png" alt="logo" />
    <p class="go_home">
      <a @click="$router.push({ path: '/', query: { isLogin: fasle } })">
        进入网站首页>></a
      >
    </p>
  </div>
  <div class="content">
    <img class="login-bg" src="@/assets/image/login-bg.png" alt="logo" />
    <!-- 用户登录 -->
    <el-form
      v-if="status"
      :model="loginForm"
      hide-required-asterisk
      :rules="rules"
      ref="validateForm"
      label-width="80px"
      class="el_ruleForm"
    >
      <el-form-item label="账户" prop="account">
        <el-input
          v-model="loginForm.account"
          placeholder="请输入账户"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="verify_code">
        <div class="verify-code">
          <el-input
            v-model="loginForm.verify_code"
            placeholder="请输入验证码"
          ></el-input>
          <el-button
            type="primary"
            @click="send_code"
            :disabled="isCooldownTime"
          >
            {{ cooldownTime > 0 ? `${cooldownTime}s后重新发送` : "发送验证码" }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item prop="agree">
        <el-checkbox
          checked
          v-model="loginForm.agree"
          label="我已同意隐私条款和服务条款"
          name="agree"
        ></el-checkbox>
      </el-form-item>
      <p class="tip">还没有账户?<a class="go_regist" @click="changeStatus">立即注册</a></p>
      <el-form-item>
        <el-button
          class="login_btn"
          size="large"
          type="primary"
          @click="submitForm('loginForm')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 用户注册 -->
    <el-form
      v-else
      :model="registerForm"
      hide-required-asterisk
      :rules="rules"
      ref="validateForm"
      label-width="80px"
      class="el_ruleForm"
    >
      <el-form-item label="账户" prop="account">
        <el-input
          v-model="registerForm.account"
          placeholder="请输入账户"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="registerForm.phone"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirm_password">
        <el-input
          v-model="registerForm.confirm_password"
          type="password"
          placeholder="请再次输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="verify_code">
        <div class="verify-code">
          <el-input
            v-model="registerForm.verify_code"
            placeholder="请输入验证码"
          ></el-input>
          <el-button
            type="primary"
            @click="send_code"
            :disabled="isCooldownTime"
          >
            {{ cooldownTime > 0 ? `${cooldownTime}s后重新发送` : "发送验证码" }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item prop="agree">
        <el-checkbox
          checked
          v-model="registerForm.agree"
          label="我已同意隐私条款和服务条款"
          name="agree"
        ></el-checkbox>
      </el-form-item>
      <p class="tip">已有账户?<a class="go_regist" @click="changeStatus">立即登入</a></p>
      <el-form-item>
        <el-button
          class="login_btn"
          size="large"
          type="primary"
          @click="submitForm('loginForm')"
          >注册</el-button
        >
      </el-form-item>
    </el-form>
  </div>
  <div class="footer_info">
    <FooterInfo />
  </div>
</template>

<script setup>
import FooterInfo from "../Layout/components/FooterInfo.vue";
import { ref,watch } from "vue";
import { useRouter,useRoute } from "vue-router";
import { useUserStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import "element-plus/dist/index.css";

const userStore = useUserStore();
const router = useRouter();
const route = useRoute()
const status = ref(route.query.status === 'true')

const isFirstChange = ref(true)
//获取表单实例
const validateForm = ref(null);
//冷却时间
const cooldownTime = ref(0);
//控制发送验证码按钮的是否禁用
const isCooldownTime = ref(false);

//登录
const loginForm = ref({
  account: "",
  password: "",
  verify_code: "",
  agree: false,
});

//注册
const registerForm = ref({
  account: "",
  phone:"",
  password: "",
  confirm_password:"",
  verify_code: "",
  agree: false,
});

const changeStatus = ()=>{
  status.value = !status.value
  if (isFirstChange.value) {
    resetForm(true) // 第一次切换时完全重置
    isFirstChange.value = false
  } else {
    resetForm(false) // 后续切换时不重置验证码相关状态
  }
}
//自定义校验是否勾选
const isAgree = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请勾选用户协议"));
  }
  //无论成功还是失败,都要调用callback()
  callback();
};
//判断两次密码是否一致
const isSame = (rule, value, callback)=>{
  if (value !== registerForm.value.password ) {
    callback(new Error("两次密码不一致,请重新输入"));
  }
  //无论成功还是失败,都要调用callback()
  callback();
}
//判断验证码是否正确
const verifyCode = ref("");
const isRight = (rule, value, callback) => {
  if (value != verifyCode.value) {
    callback(new Error("验证码错误,请重新输入"));
  }
  callback();
};
//规则对象
const rules = {
  account: [
    //失去焦点时触发
    { required: true, message: "用户名不能为空", trigger: "blur" },
  ],
  phone:[
    { required: true, message: "手机号不能为空", trigger: "blur" },
    { min: 11, max: 11, message: "请输入有效的11位手机号", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 6, max: 14, message: "长度在 6 到 14 个字符", trigger: "blur" },
  ],
  confirm_password:[
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 6, max: 14, message: "长度在 6 到 14 个字符", trigger: "blur" },
    { validator: isSame, trigger: "blur" },
  ],
  verify_code: [
    { validator: isRight, trigger: "blur" },
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "请输入4位验证码", trigger: "blur" },
  ],
  agree: [{ validator: isAgree }],
};

//登入按钮
const submitForm = () => {
  const { account, password } = loginForm.value;
  validateForm.value.validate(async (valid) => {
    //valid: 所有表单都通过校验,才为true
    if (valid) {
      if(status.value){
        try {
          await userStore.getUserInfo({ account, password });
          ElMessage({ type: "success", message: "登录成功" });
          router.push({
            path: "/",
          });
        } catch (error) {
          console.error("登录失败:", error);
        }
      }else{
        try {
          ElMessage({ type: "success", message: "注册成功" });
          router.push({
            path: "/",
          });
        } catch (error) {
          console.error("注册失败:", error);
        }
      }
    } else {
      console.log("error");
    }
  });
};
// 监听路由变化，重置 isFirstChange
watch(() => route.fullPath, () => {
  isFirstChange.value = true
})
//重置表单
const resetForm = (resetVerifyCode = false) => {
  if (status.value) {
    loginForm.value = {
      account: "",
      password: "",
      verify_code: "",
      agree: false,
    }
  } else {
    registerForm.value = {
      account: "",
      phone: "",
      password: "",
      confirm_password: "",
      verify_code: "",
      agree: false,
    }
  }
  validateForm.value.resetFields()
  
  if (resetVerifyCode) {
    cooldownTime.value = 0
    isCooldownTime.value = false
    verifyCode.value = ""
  }
}
//发送验证码按钮
const send_code = () => {
  verifyCode.value = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
  console.log(verifyCode.value);
  cooldownTime.value = 60;
  //冷却时间内禁用发送按钮
  if(!status.value){
    isCooldownTime.value = true;
  }
  const timer = setInterval(() => {
    cooldownTime.value--;
    if (cooldownTime.value <= 0) {
      isCooldownTime.value = false;
      clearInterval(timer);
    }
  }, 1000);
};
</script>

<style lang="scss" scoped>
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px 200px;

  .logo {
    width: 200px;
    height: auto;
    background: white;
  }

  .go_home {
    font-size: 16px;

    a {
      color: #333;
      text-decoration: none;

      &:hover {
        color: #40e0d0;
      }
    }
  }
}

.content {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 600px;

  .login-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .el_ruleForm {
    position: relative;
    z-index: 300;
    margin-left: 500px;
    background: white;
    width: 400px;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    .tip {
      padding-left: 100px;
      .go_regist {
        padding-left: 5px;
        color: #2b6de7;
        cursor: pointer;
      }
    }
    .verify-code {
      display: flex;
      gap: 10px;
      align-items: center;

      .el-input {
        flex: 1;
      }
    }
    .el-button {
      border: 0;
    }
    .el-form-item__content {
      display: flex;
      justify-content: space-between;
    }
    .login_btn {
      margin-top: 5px;
      width: 200px;
    }
  }
}

.footer_info {
  background: white;
  padding: 30px 0;
}
</style>